package org.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.example.common.R;
import org.example.dto.DishDto;
import org.example.entity.*;
import org.example.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private SetmealService setmealService;
    @PostMapping
    @CacheEvict(value = "dish",allEntries = true)
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        String key= "dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        dishService.saveWithFlavor(dishDto);
        return R.success("添加成功");
    }

    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        Page<Dish> pageInfo=new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage=new Page<>();

        LambdaQueryWrapper<Dish> lambdaQueryWrapper=new LambdaQueryWrapper<>();

        lambdaQueryWrapper.like(name!=null,Dish::getName,name);

        lambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);

        dishService.page(pageInfo,lambdaQueryWrapper);

        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");

        List<Dish> records=pageInfo.getRecords();

        List<DishDto> list=records.stream().map((item)->{
            DishDto dishDto=new DishDto();

            BeanUtils.copyProperties(item,dishDto);
            Long categoryId=item.getCategoryId();

            Category category=categoryService.getById(categoryId);
            if (category!=null){
                String categoryName=category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

    @GetMapping("/{id}")
      public R<DishDto> get(@PathVariable Long id){
        DishDto dishDto=dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    @PutMapping
    @CacheEvict(value = "dish",allEntries = true)

    public R<String> update(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);
//        Set keys=redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);
//        String key= "dish_"+dishDto.getCategoryId()+"_1";
//        redisTemplate.delete(key);
        return R.success("修改成功");
    }
//    @GetMapping("/list")
//    public R<List<Dish>> list(Dish dish){
//        LambdaQueryWrapper<Dish> lambdaQueryWrapper=new LambdaQueryWrapper<>();
//
//        lambdaQueryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
//
//        lambdaQueryWrapper.eq(Dish::getStatus,1);
//        lambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//        List<Dish> list = dishService.list(lambdaQueryWrapper);
//        return R.success(list);
//    }
    @GetMapping("/list")
    @Cacheable(value = "dish",key = "#dish.categoryId+'_'+#dish.status")
    public R<List<DishDto>> list(Dish dish){
        List<DishDto> dishDtoList=null;

    //        String key="dish_"+dish.getCategoryId()+"_"+dish.getStatus();
    //        dishDtoList= (List<DishDto>) redisTemplate.opsForValue().get(key);

        if (dishDtoList!=null){
            return R.success(dishDtoList);
        }

        LambdaQueryWrapper<Dish> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        lambdaQueryWrapper.eq(Dish::getStatus,1);
        lambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(lambdaQueryWrapper);

        dishDtoList= list.stream().map((item)->{
            DishDto dishDto=new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId=item.getCategoryId();
            Category category=categoryService.getById(categoryId);
            if (category!=null){
                String categoryName=category.getName();
                dishDto.setCategoryName(categoryName);
            }
            Long dishId=item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper1=new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> list1=dishFlavorService.list(lambdaQueryWrapper1);
            dishDto.setFlavors(list1);
            return dishDto;
        }).collect(Collectors.toList());

//        redisTemplate.opsForValue().set(key,dishDtoList);

        return R.success(dishDtoList);
    }
    @DeleteMapping
    @CacheEvict(value = "dish",allEntries = true)
    public R<String> delete(Long ids){
        dishService.remove(ids);
        return R.success("删除成功");
    }

    @PostMapping("/status/0")
    @Transactional
    @CacheEvict(value = "dish",allEntries = true)

    public R<String> status0(Long ids){
        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SetmealDish::getDishId,ids);
        List<SetmealDish> setmealDishes=setmealDishService.list(lambdaQueryWrapper);
        if (setmealDishes.size()!=0){
            SetmealDish setmealDish=setmealDishes.get(0);
            Setmeal setmeal=setmealService.getById(setmealDish.getSetmealId());
            setmeal.setStatus(0);
            setmealService.updateById(setmeal);
        }
        Dish dish= dishService.getById(ids);
        dish.setStatus(0);
        dishService.updateById(dish);
        return R.success("修改成功");
    }
    @PostMapping("/status/1")
    @CacheEvict(value = "dish",allEntries = true)

    public R<String> status1(Long ids){
        Dish dish= dishService.getById(ids);
        dish.setStatus(1);
        dishService.updateById(dish);
        return R.success("修改成功");
    }
}

